//
//  FFRedPacketsCell.m
//  LiMaoRedPackets
//
//  Created by JayLuo on 2020/8/26.
//

#import "FFRedPacketsCell.h"
#import "FFOpenRedPacketVC.h"
#import "FFRewardConfig.h"
#import "FFRedPacketsRecordVC.h"
#import "FFRedPacketsModule.h"
#import "Masonry.h"
#import "FFRedPacketsContent.h"
#import "FFPayPwdUpdateVC.h"


#define LIMRedPacketsTopContainerHeight 75.0f
#define LIMRedPacketsBottomContainerHeight 34.0f

@interface FFRedPacketsCell()
@property(nonatomic,strong) UIView *redPacketTopContainer;
@property(nonatomic,strong) UIView *redPacketBottomContainer;
@property(nonatomic,weak) UILabel *contentLabel;
@property(nonatomic,weak) UILabel *statusLabel;
@property(nonatomic,strong) NSString *redpacket_no;
@end

@implementation FFRedPacketsCell

+ (CGSize)contentSizeForMessage:(WKMessageModel *)model {
    return CGSizeMake([WKApp shared].config.messageContentMaxWidth,LIMRedPacketsTopContainerHeight + LIMRedPacketsBottomContainerHeight);
}

- (void)initUI {
    [super initUI];
    [self.messageContentView setBackgroundColor:[UIColor colorWithRed:255/255.0 green:179/255.0 blue:80/255.0 alpha:1.0]];
    self.messageContentView.layer.masksToBounds = YES;
    self.messageContentView.layer.cornerRadius = 4.0f;
    
    self.redPacketTopContainer = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 0.0f, LIMRedPacketsTopContainerHeight)];
    self.redPacketTopContainer.userInteractionEnabled = NO; // 设为NO 让事件传递下去
    [self.messageContentView addSubview:self.redPacketTopContainer];
    
    [self.redPacketTopContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.messageContentView);
        make.height.mas_equalTo(LIMRedPacketsTopContainerHeight);
    }];
    
    self.redPacketBottomContainer = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 0.0f, LIMRedPacketsBottomContainerHeight)];
    self.redPacketBottomContainer.userInteractionEnabled = NO; // 设为NO 让事件传递下去
    [self.messageContentView addSubview:self.redPacketBottomContainer];
    [self.redPacketBottomContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.messageContentView);
        make.height.mas_equalTo(LIMRedPacketsBottomContainerHeight);
    }];
    
    
    // 上半部分
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[self imageName:@"icon_hongbao_kai"]];
    [self.redPacketTopContainer addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.redPacketTopContainer).offset(16);
        make.top.equalTo(self.redPacketTopContainer).offset(15);
        make.height.equalTo(@46);
        make.width.equalTo(@35);
    }];
    
    UILabel *contentLabel = [[UILabel alloc] init];
    contentLabel.text = @"恭喜发财，大吉大利";
    contentLabel.textColor = [UIColor whiteColor];
    contentLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
    contentLabel.textAlignment = NSTextAlignmentLeft;
    contentLabel.numberOfLines = 2;
    [self.redPacketTopContainer addSubview:contentLabel];
    [contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(imageView.mas_top);
        make.left.equalTo(imageView.mas_right).offset(10);
        make.right.equalTo(self.redPacketTopContainer).offset(-20);
    }];
    _contentLabel = contentLabel;
    
    UILabel *statusLabel = [[UILabel alloc] init];
    statusLabel.text = @"未领取";
    statusLabel.textColor = [UIColor colorWithRed:255/255.0 green:224/255.0 blue:183/255.0 alpha:1.0];
    statusLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    statusLabel.textAlignment = NSTextAlignmentLeft;
    statusLabel.numberOfLines = 1;
    [self.redPacketTopContainer addSubview:statusLabel];
    [statusLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(contentLabel.mas_bottom).offset(5);
        make.left.equalTo(imageView.mas_right).offset(10);
        make.right.equalTo(self.redPacketTopContainer).offset(-20);
    }];
    _statusLabel = statusLabel;
    
    // 分割线
    UIView *lineView = [[UIView alloc] init];
    lineView.frame = CGRectMake(0,0,0,1);
    lineView.layer.backgroundColor = [UIColor colorWithRed:255/255.0 green:197/255.0 blue:121/255.0 alpha:1.0].CGColor;
    [self.redPacketTopContainer addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.redPacketTopContainer.mas_bottom);
        make.height.equalTo(@1);
        make.left.equalTo(self.redPacketTopContainer).offset(16);
        make.right.equalTo(self.redPacketTopContainer).offset(-16);
    }];
    
    // 下半部分
    UILabel *appNameLabel = [[UILabel alloc] init];
    appNameLabel.text = [NSString stringWithFormat:@"%@红包", [WKApp shared].config.appName];
    appNameLabel.textColor = [UIColor colorWithRed:255/255.0 green:232/255.0 blue:202/255.0 alpha:1.0];
    appNameLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:12];
    appNameLabel.textAlignment = NSTextAlignmentLeft;
    appNameLabel.numberOfLines = 1;
    [self.redPacketBottomContainer addSubview:appNameLabel];
    [appNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.redPacketBottomContainer).offset(16);
        make.centerY.equalTo(self.redPacketBottomContainer.mas_centerY);
    }];
    
}

- (void)refresh:(WKMessageModel *)model {
    [super refresh:model];
    
    self.trailingView.timeLbl.textColor = [UIColor whiteColor];
    
    WKMessage *message = [[WKMessageDB shared] getMessage:model.message.clientSeq];
    FFRedPacketsContent *content = (FFRedPacketsContent *)message.content;
    
    if (message) {
        // 自己发送的红包
        if ([message.fromUid isEqualToString:[WKApp shared].loginInfo.uid]) {
            _statusLabel.hidden = YES;
        }else {
            _statusLabel.hidden = NO;
        }
        _contentLabel.text = content.blessing;
        NSString *isOpen = message.extra[@"isOpen"];

        if (isOpen.intValue == 0) {
            // 更新UI
            [self.messageContentView setBackgroundColor:[UIColor colorWithRed:255/255.0 green:179/255.0 blue:80/255.0 alpha:1.0]];
            _statusLabel.text = @"未领取";
        }else {
            [self.messageContentView setBackgroundColor:[UIColor colorWithRed:255/255.0 green:204/255.0 blue:138/255.0 alpha:1.0]];
            _statusLabel.text = @"已领取";
        }
    }
    
}

- (void)onTap {
    [super onTap];
    WKMessage *message = [[WKMessageDB shared] getMessage:self.messageModel.message.clientSeq];
    FFRedPacketsContent *content = (FFRedPacketsContent *)message.content;
    __weak typeof(self) weakSelf = self;
    [[WKAPIClient sharedClient] GET:@"impay/wallet/my" parameters:nil].then(^(NSDictionary* dict){
        BOOL passwordIsSet = [dict[@"password_is_set"] boolValue];
        if (!passwordIsSet){
            [WKAlertUtil alert:LLang(@"你还未设置支付密码，是否立刻设置") buttonsStatement:@[LLang(@"否"),LLang(@"是")] chooseBlock:^(NSInteger buttonIdx) {
                if(buttonIdx == 1) {
                    [[WKNavigationManager shared] pushViewController:[FFPayPwdUpdateVC new] animated:YES];
                }
            }];
        }else{
            // 抢红包
            [[WKAPIClient sharedClient] GET:[NSString stringWithFormat:@"redpackets/%@/get",  content.redPacketNo] parameters:@{}].then(^(NSDictionary *dict){

                [weakSelf openRedPacket:dict];

            }).catch(^(NSError *error){
                
            });
        }
    }).catch(^(NSError *error){
       
    });
    
}

- (void)goRecordVC {
    int type = self.messageModel.channel.channelType;
    // 跳转
    FFRedPacketsRecordVC *vc = [[FFRedPacketsRecordVC alloc] init];
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    vc.redPacketsRecordType = type;
    [[WKNavigationManager shared] pushViewController:vc animated:YES];
}

- (void)openRedPacket:(NSDictionary *)dict {
    NSNumber *status = dict[@"status"];
    // 红包状态: 1.抢到红包 2.当前用户已开红包 3.红包被抢完了 4.已过期
    NSInteger statusMark = status.integerValue;
    NSString *sender_uid = dict[@"sender_uid"];
    self.redpacket_no = dict[@"redpacket_no"];
    // 判断群和单聊 1单聊 2群聊
    int type = self.messageModel.channel.channelType;
    // 跳转
    FFRewardConfig *info = ({
        FFRewardConfig *info   = [[FFRewardConfig alloc] init];
        info.redPacketInfoDict = dict;
        info.money         = 100.0;
        NSString *avatarString = [WKAvatarUtil getAvatar:sender_uid];
        info.avatarImageUrl = avatarString;
        info.userName  = dict[@"sender_name"];
        if (statusMark == 1) {
            info.content = dict[@"blessing"];
            info.isExpired = NO;
        }else if (statusMark == 2) {
            info.content = @"您已经领取过该红包\n 可在红包记录中查看";
            info.isExpired = YES;
        }else if (statusMark == 3) {
            info.content = @"手慢了,红包已经被抢完了\n 去红包记录中查看";
            info.isExpired = YES;
        }else if (statusMark == 4) {
            info.content = @"该红包已超过24小时 \n 如已领取，可在红包记录中查看";
            info.isExpired = YES;
        }
        
        info;
    });
    __weak typeof(self) weakSelf = self;
    
    // 单聊
    if (type == 1) {
        // 自己发红包
        if ([self.messageModel.message.fromUid isEqualToString:[WKApp shared].loginInfo.uid]) {
            // 跳转
            FFRedPacketsRecordVC *vc = [[FFRedPacketsRecordVC alloc] init];
            vc.modalPresentationStyle = UIModalPresentationFullScreen;
            vc.redPacketsRecordType = type;
            vc.redpacket_no = self.redpacket_no;
            [[WKNavigationManager shared] pushViewController:vc animated:YES];
        }else {
            
            if (statusMark == 2) {
                // 标记已打开
                WKMessage *message = [[WKMessageDB shared] getMessage:self.messageModel.message.clientSeq];
                
                if(message) {
                    message.extra = @{ @"isOpen" : @"1"}.mutableCopy;
                    [[WKSDK shared].chatManager updateMessageLocalExtra:message];
                    weakSelf.messageModel.message = message;
                    //  刷新UI
                    [weakSelf.conversationContext refreshCell:weakSelf.messageModel];
                    [weakSelf refresh:weakSelf.messageModel];
                }
                // 跳转
                FFRedPacketsRecordVC *vc = [[FFRedPacketsRecordVC alloc] init];
                vc.modalPresentationStyle = UIModalPresentationFullScreen;
                vc.redPacketsRecordType = type;
                vc.redpacket_no = self.redpacket_no;
                [[WKNavigationManager shared] pushViewController:vc animated:YES];
            }else{
                [FFOpenRedPacketVC showRedPackerWithData:info cancelBlock:^{
                    NSLog(@"取消领取");
                } finishBlock:^(FFRewardConfig *config) {
                    
                    NSDictionary *dict = config.redPacketInfoDict;
                    
                    NSNumber *status = dict[@"status"];
                    // 红包状态: 1.抢到红包 2.当前用户已开红包 3.红包被抢完了 4.已过期
                    NSInteger statusMark = status.integerValue;
                    if (statusMark == 1) {
                        int type = weakSelf.messageModel.channel.channelType;
                        NSString *channelId = weakSelf.messageModel.channel.channelId;
                        // 开红包
                        [[WKAPIClient sharedClient] POST:[NSString stringWithFormat:@"redpackets/%@/open",  weakSelf.redpacket_no] parameters:@{@"channel_id":channelId,@"channel_type":@(type)}].then(^(NSDictionary *dict){
                            
                            // 标记已打开
                            WKMessage *message = [[WKMessageDB shared] getMessage:weakSelf.messageModel.message.clientSeq];
                            
                            if(message) {
                                message.extra = @{ @"isOpen" : @"1"}.mutableCopy;
                                [[WKSDK shared].chatManager updateMessageLocalExtra:message];
                                weakSelf.messageModel.message = message;
                                //  刷新UI
                                [weakSelf.conversationContext refreshCell:weakSelf.messageModel];
                                [weakSelf refresh:weakSelf.messageModel];
                            }
                            
                            // 跳转
                            FFRedPacketsRecordVC *vc = [[FFRedPacketsRecordVC alloc] init];
                            vc.modalPresentationStyle = UIModalPresentationFullScreen;
                            vc.redPacketsRecordType = type;
                            vc.redpacket_no = weakSelf.redpacket_no;
                            [[WKNavigationManager shared] pushViewController:vc animated:YES];
                            
                            
                        }).catch(^(NSError *error){
                            
                        });
                    }else {
                        // 跳转
                        FFRedPacketsRecordVC *vc = [[FFRedPacketsRecordVC alloc] init];
                        vc.modalPresentationStyle = UIModalPresentationFullScreen;
                        vc.redPacketsRecordType = type;
                        vc.redpacket_no = self.redpacket_no;
                        [[WKNavigationManager shared] pushViewController:vc animated:YES];
                    }
                    
                }];
            }
       
        }
        
    }else {
        // 群聊
        if (statusMark == 2) {
            // 标记已打开
            WKMessage *message = [[WKMessageDB shared] getMessage:weakSelf.messageModel.message.clientSeq];
            
            if(message) {
                message.extra = @{ @"isOpen" : @"1"}.mutableCopy;
                [[WKSDK shared].chatManager updateMessageLocalExtra:message];
                weakSelf.messageModel.message = message;
                //  刷新UI
                [weakSelf.conversationContext refreshCell:weakSelf.messageModel];
                [weakSelf refresh:weakSelf.messageModel];
            }
            // 跳转
            FFRedPacketsRecordVC *vc = [[FFRedPacketsRecordVC alloc] init];
            vc.modalPresentationStyle = UIModalPresentationFullScreen;
            vc.redPacketsRecordType = type;
            vc.redpacket_no = weakSelf.redpacket_no;
            [[WKNavigationManager shared] pushViewController:vc animated:YES];
        }else {
            // 群聊
            [FFOpenRedPacketVC showRedPackerWithData:info cancelBlock:^{
                NSLog(@"取消领取");
            } finishBlock:^(FFRewardConfig *config) {
                
                NSDictionary *dict = config.redPacketInfoDict;
                
                NSNumber *status = dict[@"status"];
                // 红包状态: 1.抢到红包 2.当前用户已开红包 3.红包被抢完了 4.已过期
                NSInteger statusMark = status.integerValue;
                if (statusMark == 1) {
                    int type = weakSelf.messageModel.channel.channelType;
                    NSString *channelId = weakSelf.messageModel.channel.channelId;
                    // 开红包
                    [[WKAPIClient sharedClient] POST:[NSString stringWithFormat:@"redpackets/%@/open",  weakSelf.redpacket_no] parameters:@{@"channel_id":channelId,@"channel_type":@(type)}].then(^(NSDictionary *dict){
                        
                        // 标记已打开
                        WKMessage *message = [[WKMessageDB shared] getMessage:weakSelf.messageModel.message.clientSeq];
                        
                        if(message) {
                            message.extra = @{ @"isOpen" : @"1"}.mutableCopy;
                            [[WKSDK shared].chatManager updateMessageLocalExtra:message];
                            weakSelf.messageModel.message = message;
                            //  刷新UI
                            [weakSelf.conversationContext refreshCell:weakSelf.messageModel];
                            [weakSelf refresh:weakSelf.messageModel];
                        }
                        
                        // 跳转
                        FFRedPacketsRecordVC *vc = [[FFRedPacketsRecordVC alloc] init];
                        vc.modalPresentationStyle = UIModalPresentationFullScreen;
                        vc.redPacketsRecordType = type;
                        vc.redpacket_no = weakSelf.redpacket_no;
                        [[WKNavigationManager shared] pushViewController:vc animated:YES];
                        
                        
                    }).catch(^(NSError *error){
                        
                    });
                }else {
                    // 跳转
                    FFRedPacketsRecordVC *vc = [[FFRedPacketsRecordVC alloc] init];
                    vc.modalPresentationStyle = UIModalPresentationFullScreen;
                    vc.redPacketsRecordType = type;
                    vc.redpacket_no = self.redpacket_no;
                    [[WKNavigationManager shared] pushViewController:vc animated:YES];
                }
                
            }];
        }
 
    }
    
    
}


- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.trailingView.lim_top = self.messageContentView.lim_height - self.trailingView.lim_height - 7.0f;
    
}

+ (BOOL)hiddenBubble {
    return YES;
}

- (UIImage*)imageName:(NSString *)name {
    return [[WKApp shared] loadImage:name moduleID:[FFRedPacketsModule gmoduleId]];
}

@end
